/*
 * This file is part of b.AMP.
 *
 * b.AMP is free software: you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * b.AMP is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with b.AMP.  If not, see <http://www.gnu.org/licenses/>.
 */

#ifndef __BAMP_MESSAGE_CHANNEL_HPP__
#define __BAMP_MESSAGE_CHANNEL_HPP__

#include "message_ack.hpp"
#include "message_target.hpp"
#include <bamp/noncopyable.hpp>
#include <boost/thread.hpp>
#include <vector>


namespace bamp
{

    /**
     * Message channel. Messages dispatched through an message channel are
     * sent to all the attached message targets.
     */
    class MessageChannel : public MessageTarget, public bamp::Noncopyable
    {

    public:

        /**
         * Constructor. Initializes an message channel. Message target must be
         * attached using attach() for the dispatch() function to do anything.
         */
        MessageChannel();

        /**
         * Destructor. Detaches all message targets.
         */
        virtual ~MessageChannel();

        /**
         * Attach an message target to the channel.
         * @param target the target
         */
        void addTarget(MessageTarget& target);

        /**
         * Detach an message target from the channel.
         * @param target the target
         */
        void removeTarget(MessageTarget& target);

        /**
         * Dispatch an message, sending it to all the message targets. The
         * message acknowledgement object will be notified when the message
         * has finished being handled.
         * @param message the message
         * @param ack   message acknowledgement object
         */
        virtual void send(const Message& message, MessageAck ack);

        /**
         * Dispatch an message, sending it to all the message targets.
         * @param message the message
         */
        virtual MessageAck send(const Message& message);
    

    private:

        typedef std::vector<MessageTarget*> TargetVec;
        TargetVec    m_targets;      /// Attached message targets
        boost::mutex m_targetsMutex; /// Mutex for m_target

    }; // class MessageChannel

} // namespace bamp

#endif // __BAMP_MESSAGE_CHANNEL_HPP__
